package com.lw.carmanage.events.listeners;

import com.lw.carmanage.events.MyLoginEvent;
import com.lw.carmanage.mapper.SysLogMapper;
import com.lw.carmanage.pojo.SysLog;
import com.lw.carmanage.security.BaseUser;
import com.lw.carmanage.utils.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/30 21:59
 */
@Component
public class MyLoginEVentListener {


    private Logger logger = LoggerFactory.getLogger(MyLoginEVentListener.class);

    private SysLogMapper logMapper;

    @Autowired
    public void setLogMapper(SysLogMapper logMapper) {
        this.logMapper = logMapper;
    }

    @EventListener
    public void onEvent(MyLoginEvent event){
       try {
           logger.error("收到登录操作的事件了");
           ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
           HttpServletRequest request = requestAttributes.getRequest();
           BaseUser user = (BaseUser) request.getSession().getAttribute("user");
           CompletableFuture.runAsync(()->{
               SysLog sysLog=new SysLog();
               String ip = RequestUtil.getRemoteHost(request);

               sysLog.setIp(ip);
               sysLog.setId(user.getUserId());
               sysLog.setUsername(event.getLoginUserName());
               sysLog.setOperation("登录成功");
               String method = request.getMethod();
               sysLog.setMethod(method);
               sysLog.setParams("登录");
               sysLog.setCreateDate(new Date());
               logMapper.addLog(sysLog);
           });
       }catch (Exception e){
           e.printStackTrace();
       }
    }
}
